package spring.component;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.Resource;

@Service
public class BookService {
    @Qualifier("bookDao")
    @Autowired
    BookDao dao2;


    @Override
    public String toString() {
        return "BookService{" +
                "dao=" + dao2 +
                '}';
    }

    @Transactional
    public void addRecord(){
        dao2.insert();
    }

//    @Autowired //注入不成功？？
//    @Qualifier("transactionManager")//配上名字

    @Resource  //注入OK
    public PlatformTransactionManager transactionManager;
    public void addRecord2(){

        DefaultTransactionDefinition defaultTransactionDefinition = new DefaultTransactionDefinition();
        TransactionStatus transactionStatus = transactionManager.getTransaction(defaultTransactionDefinition);
        try {
            dao2.insert();
            transactionManager.commit(transactionStatus);
        }catch (Exception e){
            transactionManager.rollback(transactionStatus);
        }finally {
            System.out.println(transactionStatus);
        }
    }
}
